package com.zhongshengnetwork.rightbe.lang.activity;

import android.content.Context;
import android.os.Handler;
//import android.support.annotation.NonNull;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DateUtil;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.KeyMapDailog;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.FeedModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContactUSActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{

    private List<FeedModel> list = null;
    private ListView listview;
    private TopBarView topbar;
    private AVLoadingIndicatorView avi;
    private RefreshLayout mRefreshLayout;
    private int pageindex = 0;
    private static final int Records = 20;
    private MyAdapter adapter;
    //评论弹出框
    private KeyMapDailog dialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_us);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getRightTextView().setVisibility(View.VISIBLE);
        topbar.getRightTextView().setText("提交");
        topbar.getRightTextView().setTextSize(16);
        topbar.getRightTextView().setTextColor(getResources().getColor(R.color.mainColor));
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                feed();
            }
        });

        avi = (AVLoadingIndicatorView) findViewById(R.id.avi);
        listview = (ListView) findViewById(R.id.contactus_listview);

        list = new ArrayList<FeedModel>();

        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                feed();
            }
        });

        mRefreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        //设置 Header 为 贝塞尔雷达 样式
        mRefreshLayout.setRefreshHeader(new BezierRadarHeader(ContactUSActivity.this).setEnableHorizontalDrag(true));//BezierRadarHeader
        //设置 Footer 为 球脉冲 样式
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(ContactUSActivity.this).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
        mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
        mRefreshLayout.setEnableRefresh(true);//启用刷新
        mRefreshLayout.setEnableLoadMore(true);//启用加载
        //刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //refreshlayout.finishRefresh();
                getData();
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //refreshLayout.finishLoadMore();
                loadMore();
            }
        });
        avi.show();
        getData();

    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        hintKeyBoard();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void getData(){
        pageindex = 0;
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("pageIndex",pageindex+"");
        map.put("pageRecord",Records+"");
        HttpsUtils.feedlistDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            avi.hide();
                            mRefreshLayout.finishRefresh();
                            List<FeedModel> l = GsonTools.getFeedModel(data);
                            if (l != null && l.size() > 0){
                                pageindex += 1;
                                list.clear();
                                list.addAll(l);
                                adapter.notifyDataSetChanged();
                                if (l.size() >= Records){
                                    mRefreshLayout.setEnableLoadMore(true);
                                }
                            }else {
                                mRefreshLayout.setEnableLoadMore(false);
                            }
                        }
                    });
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            avi.hide();
                            mRefreshLayout.finishRefresh();
                        }
                    });
                }

            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mRefreshLayout.finishRefresh();
                    }
                });
            }
        });
    }

    private void loadMore(){
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("pageIndex",pageindex+"");
        map.put("pageRecord",Records+"");
        HttpsUtils.feedlistDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mRefreshLayout.finishLoadMore();
                            List<FeedModel> l = GsonTools.getFeedModel(data);
                            if (l != null && l.size() > 0){
                                pageindex += 1;
                                list.addAll(l);
                                adapter.notifyDataSetChanged();
                            }else {
                                mRefreshLayout.setEnableLoadMore(false);
                            }
                        }
                    });
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mRefreshLayout.finishLoadMore();
                        }
                    });
                }

            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mRefreshLayout.finishRefresh();
                    }
                });
            }
        });
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(ContactUSActivity.this, R.layout.contact_listview_item,null);
            }
            View view=convertView;
            //view= LayoutInflater.from(getActivity()).inflate(R.layout.notify_listview_item, null);
            TextView title = (TextView) view.findViewById(R.id.notify_listview_item_title);
            TextView time = (TextView) view.findViewById(R.id.notify_listview_item_time);
            FeedModel model = list.get(position);
            title.setText(model.getContent());
            if (CommonUtils.isEmpty(model.getReply())){
                time.setText("提交成功  "+DateUtil.getChatDate(model.getTime()));
            }else {
                time.setText("回复："+model.getReply()+"  "+DateUtil.getChatDate((long)model.getReplytime()*1000));
            }
            title.setTextColor(getResources().getColor(R.color.defaultFontColor));
            time.setTextColor(getResources().getColor(R.color.defaultSmallFontColor));

            return view;
        }
    }

    private void feed(){
        dialog = new KeyMapDailog("请输入你的意见反馈或者诉求......", new KeyMapDailog.SendBackListener() {
            @Override
            public void sendBack(final String inputText) {
                if (inputText == null || inputText.length() == 0){
                    return;
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //dialog.hideProgressdialog();
                        dialog.dismiss();

                        KyLoadingBuilder dialog = new KyLoadingBuilder(ContactUSActivity.this);
                        dialog.setIcon(R.drawable.loading04);
                        dialog.setText("正在提交...");
                        dialog.setOutsideTouchable(false);//点击空白区域是否关闭
                        dialog.setBackTouchable(true);//按返回键是否关闭
                        dialog.show();
                        final Map<String,String> map = new HashMap<String, String>();
                        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                        map.put(APIKey.contentKey,inputText);
                        HttpsUtils.feedDo(map, new HttpCallBack() {
                            @Override
                            public void onSuccess(String data) {
                                dialog.dismiss();
                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                if (commonModel.getFlag().equals("1")){
                                    ToastUtil.show(ContactUSActivity.this,"提交成功");
                                    getData();
                                }else {
                                    CustomApplication.showTip(commonModel,ContactUSActivity.this);
                                }
                            }

                            @Override
                            public void onError(String msg) {
                                dialog.dismiss();
                            }
                        });
                    }
                }, 10);
            }
        });
        dialog.show(getSupportFragmentManager(), "dialog");
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

}
